// PixelationPostProcessing.cs

using System;
using UnityEngine;

[ExecuteInEditMode]
[RequireComponent(typeof(Camera))]
public class PixelationPostProcessing : MonoBehaviour
{
    [Header("Pixelation Settings")]
    public Shader pixelationShader;
    public float pixelSize = 10f;
    
    private Material pixelationMaterial;
    private Camera cam;

    private void Update()
    {
        pixelSize = Mathf.PingPong(Time.time*20, 246)+10;
    }

    void Start()
    {
        cam = GetComponent<Camera>();
        
        // 初始化Shader和材质
        if (pixelationShader == null)
            pixelationShader = Shader.Find("Custom/PixelationPostProcessing");
            
        if (pixelationShader != null)
            pixelationMaterial = new Material(pixelationShader);
    }
    
    void OnRenderImage(RenderTexture source, RenderTexture destination)
    {
        if (pixelationMaterial != null)
        {
            // 设置像素大小参数
            pixelationMaterial.SetFloat("_PixelSize", pixelSize);
            
            // 应用后处理效果
            Graphics.Blit(source, destination, pixelationMaterial);
        }
        else
        {
            // 如果没有材质，直接输出原始图像
            Graphics.Blit(source, destination);
        }
    }
}